import request from '@/utils/request'

export default {
  query: function (params) {
    return request({
      url: '/riskList/getRiskPage',
      method: 'get',
      params
    })
  },
  get: function (id) {
    return request({
      url: '/riskList/getReportRiskList?id=' + id,
      method: 'get'
    })
  },
  insert: function (data) {
    return request({
      url: '/riskList/addRiskList',
      method: 'post',
      data: data
    })
  },
  update: function (data) {
    return request({
      url: '/riskList/modRiskList',
      method: 'post',
      data: data
    })
  },
  del: function (id) {
    return request({
      url: '/riskList/delRiskById',
      method: 'post',
      data: { id }
    })
  },
  all: function (tabName) {
    return new Promise((resolve) => {
      const key = "all-risk-libs--" + tabName
      const localDataStr = sessionStorage.getItem(key)
      try {
        if (localDataStr === null) throw "null"
        const localData = JSON.parse(localDataStr)
        resolve(localData)
      } catch (e) {
        request({
          url: '/riskList/getAllData',
          method: 'get',
          params: { tabName }
        }).then(res => {
          const data = setLevel(res.data)
          sessionStorage.setItem(key, JSON.stringify(data))
          resolve(data)
        })
      }
    })
  },
  tree: function (tabName) {
    return new Promise((resolve) => {
      this.all(tabName).then(list => {
        resolve(list2Tree(list))
      })
    })
  },
  queryChildDataByParentId: function (tabName, parentId) {
    return new Promise(resolve => {
      this.all(tabName).then(list => {
        resolve(list.filter(item => item.parentId == parentId))
      })
    })
  },
  export: '/jobReport/exportReport'
}


function list2Tree(list) {
  const newList = list.filter(item => item.parentId === 0)
  return newList.map(first => {
    first.children = list.filter(sec => sec.parentId === first.id).map(sec => {
      sec.children = list.filter(t => t.parentId === sec.id)
      return sec
    })
    return first
  })
}

function setLevel(list) {
  const fList = list.filter(item => item.parentId === 0).map(item => { item.level = 0; return item })
  const sList = list.filter(item => fList.some(f => f.id === item.parentId)).map(item => { item.level = 1; return item })
  const tList = list.filter(item => sList.some(f => f.id === item.parentId)).map(item => { item.level = 2; return item })
  return fList.concat(sList).concat(tList)
}